package com.lottery.pay.Utils.wxUtil;

import com.alibaba.fastjson.JSONObject;
import com.lottery.pay.Constants.WeixinConstant;
import com.lottery.pay.Model.weixin.User;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;

/**
 * 微信获取用户信息
 */
public class UserInfo {
	public static final Logger logger = LoggerFactory.getLogger(UserInfo.class);

	/**
	 * 根据openId获取用户资料
	 */
	public User getUserInfo(String token, String openid) {
		logger.info("token={}, openid={}", token, openid);
		String url = WeixinConstant.INFO_PATH;
		url = url.replace("ACCESS_TOKEN", token);
		url = url.replace("OPENID", openid);
		String response = HttpsUtil.getMethod(url);
		JSONObject jsonObject = JSONObject.parseObject(response);
		logger.info("userInfo={}", jsonObject);
		User user = new User(jsonObject.getString("subscribe"),
				jsonObject.getString("openid"),
				jsonObject.getString("nickname"), jsonObject.getString("sex"),
				jsonObject.getString("city"), jsonObject.getString("country"),
				jsonObject.getString("province"),
				jsonObject.getString("language"),
				jsonObject.getString("headimgurl"),
				jsonObject.getString("subscribe_time"),
				jsonObject.getString("unionid"),
				jsonObject.getString("remark"), jsonObject.getString("groupid"));
		try {
			// 消除微信昵称中的不可见字符
			if(StringUtils.isNotEmpty(jsonObject.getString("nickname"))){
				user.setNickname(MultiUtil.filterOffUtf8Mb4(jsonObject
						.getString("nickname")));
				logger.info("nickname={}", user.getNickname());
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return user;
		}
		return user;
	}

	/**
	 * 根据code获取用户openId
	 */
	public String getOpenId(String app_id, String app_secret, String code) {
		logger.info("weixin app_id={}, app_secret ={}, userCode={}", app_id, app_secret, code);
		String codeUrl = WeixinConstant.OPENID_PATH;
		codeUrl = codeUrl.replace("APPID", app_id)
				.replace("SECRET", app_secret).replace("CODE", code);
		String response = HttpsUtil.getMethod(codeUrl);
		JSONObject jsonObject = JSONObject.parseObject(response);
		String openId = jsonObject.getString("openid");
		logger.info(jsonObject.toJSONString());
		logger.info("weixin openId={}", openId);
		return openId;
	}
}
